package org.itboys.mobile.service.pos;


import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.json.JsonUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.product.SundayProductMapper;
import org.itboys.mobile.dto.pos.SundayPosShopDto;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mongo.SundayPermission;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.entity.pos.product.PosProduct;
import org.itboys.mobile.entity.pos.product.PosProductResult;
import org.itboys.mobile.entity.pos.store.PosStoreAndPrice;
import org.itboys.mobile.entity.pos.store.PosStoreAndPriceResult;
import org.itboys.mobile.service.mongo.mobile.SundayMobilePermissionService;
import org.itboys.mobile.service.mongo.web.SundayMemberService;
import org.itboys.mobile.service.pos.util.PosHttpHelper;
import org.itboys.mobile.service.pos.util.PosMD5Util;
import org.itboys.mobile.util.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 作者：jiangxiong
 * 日期：2016年7月8日
 * 联系方式 ：empty90911@126.com
 * 描述：花果山_pos_商品（同步itemCode）_
 */
@Service
public class PosProductService_ld {

	private final static Logger logger = LoggerFactory.getLogger(PosHttpHelper.class);
	public static String token = "DXa7Ay57S4Uhly7djjrVIEU6PQ7gOZCtDA3dgi8vRGs=";
	public static String url = "http://123.56.12.244:8888/standard/Execute";

	@Autowired
	private SundayProductMapper productMapper;
	@Autowired
	private SundayMemberService memberService;
	@Autowired
	private SundayMobilePermissionService permissionService;
	/**获取全品类商品**/
	public static List<PosProduct> getAllProductFromPos(){

		Map<String,Object> param =new HashMap<String, Object>();
		param.put("Method", "GetItemAll");
		//时间搓
		Long timeStamp=new Date().getTime();
		param.put("TimeStamp", timeStamp);
		Integer Page =1;
		//所有POS中所有Product
		List<PosProduct> posProducts = new ArrayList<PosProduct>();

		while(true){
			String data  = "{\"Page\":\"" + Page+ "\"}";
			//签名
			String Signature =PosMD5Util.MD5(token+timeStamp+data);
			param.put("data", data);
			param.put("Signature", Signature.toUpperCase());

			String responsResult= PosHttpHelper.doPost(url, param);


			PosProductResult result=  JsonUtils.jsonToObject(PosProductResult.class, responsResult);

			Integer code = result.ResCode;
			if(code!=0){
				throw new ErrorException(result.Msg);
			}else{
				if(result.ResData.size()==0){
					break;
				}
				for(PosProduct posProduct:result.ResData){
					posProducts.add(posProduct);
				}
				Page++;
			}

		}
		return posProducts;

	}

	public static void getAllProductFromPos2(){

		Map<String,Object> param =new HashMap<String, Object>();
		param.put("Method", "GetItemAll");
		//时间搓
		Long timeStamp=new Date().getTime();
		param.put("TimeStamp", timeStamp);
		Integer Page =1;
		//所有POS中所有Product
		//	List<PosProduct> posProducts = new ArrayList<PosProduct>();


		String data  = "{\"Page\":\"" + 1+ "\"}";
		//签名
		String Signature =PosMD5Util.MD5(token+timeStamp+data);
		param.put("data", data);
		param.put("Signature", Signature.toUpperCase());

		String responsResult= PosHttpHelper.doPost(url, param);

		logger.info("-----------------"+responsResult);



	}
	/**
	 * 从pos中同步商品的编码信息
	 * @return
	 */
	@Transactional
	public void processProductToApp(){

		//POS中存在的全品类商品
		List<PosProduct> posProducts = getAllProductFromPos();
		//查询本地APP中所属商品
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("type", SundayCommonConstants.type_mall);
		param.put("isDeleted", SundayCommonConstants.NO);
		List<SundayProduct> sundayProducts = productMapper.select(param);
		//开始同步信息。
		/**
		 * 重要-------------本次操作同步以下信息：名称，规格，赠送积分，商品编码；商品价格和库存请在门店管理中同步
		 */

		for(SundayProduct sundayProduct:sundayProducts){
			for(PosProduct posProduct:posProducts){
				if(posProduct.Barcode.equalsIgnoreCase(sundayProduct.getNumber())){
					logger.info("商品名称="+posProduct.ItemName+"，商品编码="+posProduct.Barcode+",商品规格="+posProduct.ItemSize+",商品ItemCode="+posProduct.ItemCode);
					sundayProduct.setName(posProduct.ItemName);
					sundayProduct.setViceName(posProduct.ItemName);
					sundayProduct.setStandard(posProduct.ItemSize);
					sundayProduct.setItemCode(posProduct.ItemCode);
					sundayProduct.setIsExistPos(SundayCommonConstants.YES);
					productMapper.update(sundayProduct);
					break;//在POS中找到了商品就退出查找POS
				}
			}
		}
		//}

		//	return erroProducts;
	}
	/**
	 * 获取（门店）仓库商品的库存和价格
	 * @param BranchCode
	 * @return
	 */
	public static  List<PosStoreAndPrice>  getStoreAndPriceFromPos(String BranchCode){

		Map<String,Object> param =new HashMap<String, Object>();
		param.put("Method", "GetBranchItemAll");
		//时间搓
		Long timeStamp=new Date().getTime();
		param.put("TimeStamp", timeStamp);
		Integer Page =1;
		//按照门店，获取门店所有商品的价格和库存
		List<PosStoreAndPrice> posStoreAndPrices = new ArrayList<PosStoreAndPrice>();

		while(true){
			String data = "{\"Page\":" + Page + ",\"BranchCode\":\"" + BranchCode +"\"}";
			//签名
			String Signature = PosMD5Util.MD5(token+timeStamp+data);
			param.put("data", data);
			param.put("Signature", Signature.toUpperCase());

			String responsResult= PosHttpHelper.doPost(url, param);
			logger.info("--获取门店库存和价格--"+responsResult);
			PosStoreAndPriceResult result=  JsonUtils.jsonToObject(PosStoreAndPriceResult.class, responsResult);
			Integer code = result.ResCode;
			if(code!=0){
				throw new ErrorException(result.Msg);
			}else{
				if(result.ResData.size()==0){
					break;
				}
				for(PosStoreAndPrice storeAndPrice:result.ResData){
					posStoreAndPrices.add(storeAndPrice);
				}
				Page++;
			}
		}
		return posStoreAndPrices;

	}

	/**
	 * 按门店同步商品库存，价格，
	 * 支持同步所有或单个门店同步
	 * @param branchCode
	 */
	@Transactional
	public void processStoreAndPriceToApp(String branchCode){
		Map<String,Object> param = new HashMap<String, Object>();
		List<SundayPosShopDto> shops = new ArrayList<SundayPosShopDto>();
		if(StringUtils.isNotEmpty(branchCode)){
			param.clear();
			param.put("userType", SundayCommonConstants.user_type_shop);
			param.put("isDeleted", SundayCommonConstants.NO);
			param.put("number",branchCode);
			List<SundayMember> members  =memberService.list(param);

			shops.add(new SundayPosShopDto(members.get(0).getId(),members.get(0).getNumber()));

		}else{
			param.clear();
			param.put("userType", SundayCommonConstants.user_type_shop);
			param.put("isDeleted", SundayCommonConstants.NO);
			List<SundayMember> members  =memberService.list(param);
			for(SundayMember member:members){
				shops.add(new SundayPosShopDto(member.getId(),member.getNumber()));
			}

		}
		//List<SundayPermission> newShopPermissions = new ArrayList<SundayPermission>();
		param.clear();
		//app后台所有和pos对应的商品
		param.put("type", SundayCommonConstants.type_mall);
		param.put("isDeleted", SundayCommonConstants.NO);
		param.put("status", SundayCommonConstants.YES);
		List<SundayProduct> products=productMapper.select(param);
		//所有门店旧权限
		param.clear();
		param.put("isDeleted", SundayCommonConstants.NO);
		List<SundayPermission> allOldShopPermissions = permissionService.list(param);

		//本次同步需要新增的
		List<SundayPermission> allNeedToAdd = new ArrayList<SundayPermission>();
		//本次同步需要修改的
		List<SundayPermission> allNeedToUpdate = new ArrayList<SundayPermission>();
		//本次同步需要删除的
		List<SundayPermission> allNeedToDelete = new ArrayList<SundayPermission>();
		//本次需要不变的
		List<SundayPermission> allNeedToStay = new ArrayList<SundayPermission>();


		for(SundayPosShopDto shop:shops){
			//按门店编码查询商品价格和库存
			logger.info("开始POS商品库存和价格查询"+"---门店编码----"+shop.getMemberNumber());
			List<PosStoreAndPrice>  posStoreAndPrices =getStoreAndPriceFromPos(shop.getMemberNumber());
			logger.info("结束POS商品库存查询和价格"+"---门店编码----"+branchCode+"POS中共有"+posStoreAndPrices.size()+"数据");
			List<SundayPermission> newShopPermissions = new ArrayList<SundayPermission>();
			for(PosStoreAndPrice posStoreAndPrice:posStoreAndPrices){
				for(SundayProduct product:products){
					//只查询编码对应的商品
					if(posStoreAndPrice.Barcode.equalsIgnoreCase(product.getNumber())){
						logger.info("开始POS商品库存和价格查询"+"---门店编码----"+branchCode+"--匹配到的商品编码--"+posStoreAndPrice.Barcode+"--库存--="+posStoreAndPrice.StockQty);
						SundayPermission newShopPermission =
								new SundayPermission(
										shop.getMemberId(),shop.getMemberNumber(),
										product.getId(), product.getNumber(),
										product.getName(), product.getStandard(),
										posStoreAndPrice.StockQty,posStoreAndPrice.SalePrice.doubleValue());
						newShopPermissions.add(newShopPermission);
						break;
					}
				}
			}
			logger.info("结束POS商品库存查询和价格"+"---门店编码----"+branchCode+"APP共有"+newShopPermissions.size()+"数据");

			//当前门店旧的权限
			List<SundayPermission> oldShopPermissions =new ArrayList<SundayPermission>();
			for(SundayPermission allOldShopPermission:allOldShopPermissions){
				if(LongUtil.isNotZreo(allOldShopPermission.getMemberId())&&
						allOldShopPermission.getMemberId().longValue()==shop.getMemberId().longValue()&&
						allOldShopPermission.getMemberNumber().equalsIgnoreCase(shop.getMemberNumber())){
					oldShopPermissions.add(allOldShopPermission);

				}
			}
			//查询门店是否是第一次更新权限数据
			//不是第一次更新数据
			if(ListUtil.isNotNull(oldShopPermissions)){
				//找出当前门店需要新增,修改,删除，保持不变的数据的数据
				//找出当前门店需要修改的数据
				List<SundayPermission> needToAdd = new ArrayList<SundayPermission>();
				List<SundayPermission> needToUpdate = new ArrayList<SundayPermission>();
				//	List<SundayPermission> needToDelete = new ArrayList<SundayPermission>();
				List<SundayPermission> needToStay = new ArrayList<SundayPermission>();

				boolean isNeedToAdd =true;
				for(SundayPermission newShopPermission:newShopPermissions){
					for(SundayPermission oldShopPermission:oldShopPermissions){
						if(oldShopPermission.getProductNo().equalsIgnoreCase(newShopPermission.getProductNo())){
							isNeedToAdd=false;
							if(oldShopPermission.getStore()==newShopPermission.getStore()){
								// isNeedToUpdate=true;
								needToStay.add(oldShopPermission);
							}else{
								oldShopPermission.setStore(newShopPermission.getStore());
								allNeedToUpdate.add(oldShopPermission);
							}
							break;
						}
					}
					if(isNeedToAdd){
						allNeedToAdd.add(newShopPermission);
					}
				}
				//找出当前门店需要删除的数据
				//在旧数据中删除掉要修改的和保持不变的，就是需要删除的
				oldShopPermissions.removeAll(allNeedToUpdate);
				oldShopPermissions.removeAll(allNeedToStay);
				allNeedToDelete.addAll(oldShopPermissions);

				//是第一次更新数据
			}else{
				//新增本次查询到所有商品库存和价格
				if(ListUtil.isNotNull(newShopPermissions)){
					allNeedToAdd.addAll(newShopPermissions);
				}
			}
		}
		//新增
		logger.info("本次同步新增的数据="+allNeedToAdd.size()+"条");
		if(ListUtil.isNotNull(allNeedToAdd)){
			permissionService.batchSaveWithoutLogin(allNeedToAdd);
		}
		//修改
		logger.info("本次同步修改的数据="+allNeedToUpdate.size()+"条");
		if(ListUtil.isNotNull(allNeedToUpdate)){
			permissionService.batchSaveWithoutLogin(allNeedToUpdate);
		}
		logger.info("本次同步删除的数据="+allNeedToDelete.size()+"条");
		if(ListUtil.isNotNull(allNeedToDelete)){
			permissionService.batchDeletedWithoutLogin(allNeedToDelete);
		}
		//删除
		logger.info("结束更新库存");


	}
	public static void main(String[] args) {
		//67146439
		//processProductToApp();
	}

}
